package com.jc.service.common.config;

import com.jc.service.common.interceptor.JwtAuthInterceptor;
import com.jc.service.common.interceptor.TenantIdValidationInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web配置类，用于注册拦截器
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final JwtAuthInterceptor jwtAuthInterceptor;
    private final TenantIdValidationInterceptor tenantIdValidationInterceptor;

    public WebMvcConfig(JwtAuthInterceptor jwtAuthInterceptor, 
                        TenantIdValidationInterceptor tenantIdValidationInterceptor) {
        this.jwtAuthInterceptor = jwtAuthInterceptor;
        this.tenantIdValidationInterceptor = tenantIdValidationInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册JWT认证拦截器，拦截所有API请求
        registry.addInterceptor(jwtAuthInterceptor)
                .addPathPatterns("/api/**")
                // 可以在这里添加不需要认证的路径
                .excludePathPatterns("/api/auth/login");
        
        // 注册租户ID验证拦截器，拦截包含租户ID的API路径
        registry.addInterceptor(tenantIdValidationInterceptor)
                .addPathPatterns("/api/v1/tenants/*/**")
                // 匹配形如 /api/{tenantId}/resource 的路径
                .excludePathPatterns("/api/auth/login");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}